package org.fastiot.gateway

import org.apache.camel.CamelContext
import org.apache.camel.builder.RouteBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class RouteConfiguration {

    @Bean
    SocketAccessRegistrar accessRegistrar() {
        new SocketAccessRegistrar()
    }

    static class SocketAccessRegistrar {

        @Autowired
        CamelContext camelContext

        private SocketAccessRegistrar() {}

        def register(final Connector config) {
            camelContext.addRoutes(new RouteBuilder() {
                @Override
                void configure() throws Exception {
                    if (config.type == Connector.Type.Server) {
                        from("netty4:tcp://$config.host:$config.port?decoders=#bytePacketDecoder&encoders=#bytePacketEncoder&sync=false")
                                .to("bean:serverMessageProcessor?method=receive")
                    } else if (config.type == Connector.Type.Client) {
                        from("seda:send.message")
                                .to("bean:clientMessageProcessor?method=encode")
                                .to("netty4:tcp://$config.host:$config.port?clientInitializerFactory=#initializerFactory&sync=false")
                    }
                }
            })
        }
    }
}
